<template>
  <div>
    <canvas ref="canvas" width="360" height="240"></canvas>
    <!-- 假设每个小球直径为20，间距为5 -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      gridSizeX: 9, // 网格宽度（列数）
      gridSizeY: 6, // 网格高度（行数）
      ballSize: 20,
      padding: 5,
      selectedIndexes: [2, 1, 6, 0, 1, 5], // 每一行中选定的小球索引（从0开始）
      canvasRef: null,
    };
  },
  mounted() {
    this.canvasRef = this.$refs.canvas;
    this.drawCanvas();
  },
  methods: {
    getPosition(rowIndex, columnIndex) {
      // 计算小球的位置
      const x = columnIndex * (this.ballSize + this.padding) + this.padding;
      const y = rowIndex * (this.ballSize + this.padding) + this.padding;
      return { x, y };
    },
    drawBall(ctx, rowIndex, columnIndex) {
      // 绘制小球
      const position = this.getPosition(rowIndex, columnIndex);
      ctx.beginPath();
      ctx.arc(
        position.x + this.ballSize / 2,
        position.y + this.ballSize / 2,
        this.ballSize / 2,
        0,
        2 * Math.PI
      );
      ctx.fillStyle = "red";
      ctx.fill();
      ctx.closePath();
    },
    drawCanvas() {
      const ctx = this.canvasRef.getContext("2d");

      // 清除画布
      ctx.clearRect(0, 0, this.canvasRef.width, this.canvasRef.height);

      // 绘制小球
      for (let rowIndex = 0; rowIndex < this.gridSizeY; rowIndex++) {
        const columnIndex = this.selectedIndexes[rowIndex]; // 假设selectedIndexes与行索引一一对应
        if (columnIndex >= 0 && columnIndex < this.gridSizeX) {
          this.drawBall(ctx, rowIndex, columnIndex);
        }
      }

      // 绘制连接线
      for (let i = 0; i < this.selectedIndexes.length - 1; i++) {
        const fromRowIndex = i;
        const fromColumnIndex = this.selectedIndexes[i];
        const toRowIndex = i + 1;
        const toColumnIndex = this.selectedIndexes[i + 1];

        // 计算起点和终点的位置
        const fromPos = this.getPosition(fromRowIndex, fromColumnIndex);
        const toPos = this.getPosition(toRowIndex, toColumnIndex);

        // 绘制连接线
        ctx.beginPath();
        ctx.moveTo(
          fromPos.x + this.ballSize / 2,
          fromPos.y + this.ballSize / 2
        );
        ctx.lineTo(toPos.x + this.ballSize / 2, toPos.y + this.ballSize / 2);
        ctx.strokeStyle = "blue";
        ctx.lineWidth = 2;
        ctx.stroke();
        ctx.closePath();
      }
    },
  },
};
</script>

<style scoped>
canvas {
  border: 1px solid black;
}
</style>
